const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

// 测试数据配置
const testData = {
  shopCategories: [
    {
      name: '水果',
      icon: 'https://example.com/icons/fruit.png',
      sort: 1
    },
    {
      name: '蔬菜',
      icon: 'https://example.com/icons/vegetable.png',
      sort: 2
    },
    {
      name: '生鲜',
      icon: 'https://example.com/icons/meat.png',
      sort: 3
    },
    {
      name: '零食',
      icon: 'https://example.com/icons/snack.png',
      sort: 4
    },
    {
      name: '饮品',
      icon: 'https://example.com/icons/drink.png',
      sort: 5
    }
  ],
  shops: [
    {
      name: '水果店',
      logo: 'https://example.com/shops/fruit.jpg',
      cover: 'https://example.com/shops/fruit-cover.jpg',
      description: '专注经营各类新鲜水果，果园直供',
      address: '广州市天河区天河路123号',
      phone: '020-12345678',
      businessHours: '09:00-21:00',
      rating: 4.8,
      monthlySales: 1234,
      location: {
        latitude: 23.13,
        longitude: 113.32
      },
      distance: 0, // 将在查询时计算
      status: 'open',
      categories: ['水果']
    },
    {
      name: '蔬菜店',
      logo: 'https://img01.yzcdn.cn/vant/leaf.jpg',
      cover: 'https://img01.yzcdn.cn/vant/tree.jpg',
      description: '专注经营各类新鲜蔬菜，产地直供',
      address: '广州市天河区体育西路456号',
      phone: '020-87654321',
      businessHours: '08:00-20:00',
      rating: 4.7,
      monthlySales: 2345,
      categories: ['蔬菜']
    }
  ],
  categories: [
    {
      name: '水果',
      icon: 'https://img01.yzcdn.cn/vant/apple-1.jpg',
      sort: 1,
      shopId: '',
      products: [
        {
          name: '红富士苹果',
          price: 5.99,
          originalPrice: 7.99,
          stock: 100,
          description: '山东烟台红富士苹果，果园直供，新鲜采摘',
          images: [
            'https://img01.yzcdn.cn/vant/apple-1.jpg',
            'https://img01.yzcdn.cn/vant/apple-2.jpg'
          ],
          sales: 58,
          rating: 4.8
        },
        {
          name: '海南香蕉',
          price: 3.99,
          originalPrice: 4.99,
          stock: 150,
          description: '海南香蕉，自然熟化，香甜可口',
          images: [
            'https://img01.yzcdn.cn/vant/cat.jpeg',
            'https://img01.yzcdn.cn/vant/cat.jpeg'
          ],
          sales: 42,
          rating: 4.7
        }
      ]
    },
    {
      name: '蔬菜',
      icon: 'https://img01.yzcdn.cn/vant/leaf.jpg',
      sort: 2,
      products: [
        {
          name: '有机生菜',
          price: 2.99,
          originalPrice: 3.99,
          stock: 80,
          description: '有机水培生菜，无农药残留，新鲜采摘',
          images: [
            'https://img01.yzcdn.cn/vant/leaf.jpg',
            'https://img01.yzcdn.cn/vant/tree.jpg'
          ],
          sales: 35,
          rating: 4.6
        },
        {
          name: '西红柿',
          price: 4.99,
          originalPrice: 5.99,
          stock: 120,
          description: '温室栽培西红柿，个大汁多，新鲜采摘',
          images: [
            'https://img01.yzcdn.cn/vant/sand.jpg',
            'https://img01.yzcdn.cn/vant/sand.jpg'
          ],
          sales: 67,
          rating: 4.9
        }
      ]
    }
  ]
}

exports.main = async (event, context) => {
  const db = cloud.database()
  
  try {
    // 清空现有数据
    const _ = db.command
    
    console.log('开始初始化测试数据...')
    try {
      // 确保集合存在
      try {
        await db.createCollection('shopCategories')
        console.log('创建shopCategories集合成功')
      } catch (e) {
        console.log('shopCategories集合已存在')
      }
 
      try {
        await db.createCollection('shops')
        console.log('创建shops集合成功')
      } catch (e) {
        console.log('shops集合已存在')
      }
 
      try {
        await db.createCollection('categories')
        console.log('创建categories集合成功')
      } catch (e) {
        console.log('categories集合已存在')
      }
 
      try {
        await db.createCollection('products')
        console.log('创建products集合成功')
      } catch (e) {
        console.log('products集合已存在')
      }
 
      // 清空旧数据
      await db.collection('shopCategories').where({
        _id: _.exists(true)
      }).remove()
      
      await db.collection('shops').where({
        _id: _.exists(true)
      }).remove()
      
      await db.collection('categories').where({
        _id: _.exists(true)
      }).remove()
      
      await db.collection('products').where({
        _id: _.exists(true)
      }).remove()
      console.log('清空旧数据成功')
    } catch (e) {
      console.log('清空数据失败（可能是集合不存在）：', e)
    }
    
    // 添加店铺分类
    for (const category of testData.shopCategories) {
      await db.collection('shopCategories').add({
        data: {
          ...category,
          createTime: db.serverDate()
        }
      })
      console.log('添加店铺分类成功:', category.name)
    }
    
    // 添加店铺数据
    for (const shop of testData.shops) {
      const { _id: shopId } = await db.collection('shops').add({
        data: {
          ...shop,
          status: 'open',
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
      console.log('添加店铺成功:', shop.name, 'ID:', shopId)
      
      // 为对应类别的商品设置店铺ID
      for (const category of testData.categories) {
        if (shop.categories.includes(category.name)) {
          category.shopId = shopId
        }
      }
    }
    
    // 添加分类和商品数据
    for (const category of testData.categories) {
      const { products, ...categoryData } = category
      
      const { _id: categoryId } = await db.collection('categories').add({
        data: {
          ...categoryData,
          shopId: categoryData.shopId,
          createTime: db.serverDate()
        }
      })
      
      // 添加该分类下的所有商品
      for (const product of products) {
        try {
          const result = await db.collection('products').add({
            data: {
              ...product,
              categoryId,
              shopId: categoryData.shopId,
              status: 'on',
              tags: [],
              createTime: db.serverDate(),
              updateTime: db.serverDate()
            }
          })
          console.log('添加商品成功:', product.name, 'ID:', result._id)
        } catch (e) {
          console.error('添加商品失败:', product.name, e)
          throw e
        }
      }
    }
    
    // 验证数据是否添加成功
    const shopsCount = await db.collection('shops').count()
    const categoriesCount = await db.collection('categories').count()
    const productsCount = await db.collection('products').count()
    
    return {
      success: true,
      message: `初始化成功：${shopsCount.total}个店铺，${categoriesCount.total}个分类，${productsCount.total}个商品`
    }
  } catch (error) {
    console.error('初始化数据失败：', error)
    return {
      success: false,
      message: '测试数据初始化失败',
      error: error.message || error
    }
  }
} 